<?php

namespace Henan\ThinkSdk\utils;

use PHPQRCode\QRcode;

/**
 * 二维码工具类
 */
class QrcodeUtil
{
    /**
     * 二维码GD图像
     * @var false|\GdImage|resource
     */
    protected $qrcode;

    /**
     * 构造函数
     * @param string $text 二维码内容
     * @param int $size 二维码大小
     * @param int $margin 二维码边缘大小
     * @param string $level 二维码纠错级别
     */
    public function __construct(string $text, int $size = 10, int $margin = 1, string $level = 'H')
    {
        ob_start();
        QRcode::png($text, false, $level, $size, $margin);
        $string = ob_get_contents();
        ob_end_clean();
        $this->qrcode = ImageUtil::trueColor(imagecreatefromstring($string));
    }

    /**
     * 设置Logo图片
     * @param string $logoImage logo图片
     * @param int $size 图片大小
     * @return $this
     */
    public function setLogo(string $logoImage, int $size = 100): QrcodeUtil
    {

        // 创建一个中心图片
        $content = file_get_contents($logoImage); //获取图片内容
        $centerImage = imagecreatefromstring($content); //从字符串的图像流中新建图像
        $centerImage = imagescale($centerImage, $size, $size);
        // 将中心图像添加到QR码中
        $qrCodeWidth = imagesx($this->qrcode);
        $qrCodeHeight = imagesy($this->qrcode);
        $centerImageWidth = imagesx($centerImage);
        $centerImageHeight = imagesy($centerImage);
        $im = imagecreatetruecolor($centerImageWidth + 10, $centerImageHeight + 10);
        $color = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $color);
        $im = ImageUtil::borderRadius($im);
        $centerImage = ImageUtil::borderRadius($centerImage);
        imagecopy($im, $centerImage, 5, 5, 0, 0, $centerImageWidth, $centerImageHeight);
        $centerImageX = ($qrCodeWidth - $centerImageWidth) / 2;
        $centerImageY = ($qrCodeHeight - $centerImageHeight) / 2;
        // 将中间图片复制到二维码图片上
        imagecopy($this->qrcode, $im, $centerImageX - 5, $centerImageY - 5, 0, 0, $centerImageWidth + 10, $centerImageHeight + 10);
        return $this;
    }

    /**
     * 保存图片
     * @param string $outfile 保存图片路径
     * @param bool $isBase64 是否输出base64
     * @return bool|string
     */
    public function save(string $outfile = '', bool $isBase64 = true)
    {
        if ($isBase64) {
            ob_start();
            imagepng($this->qrcode);
            $string = ob_get_contents();
            ob_end_clean();
            imagedestroy($this->qrcode); //释放内存
            return base64_encode($string);
        } else {
            if (empty($outfile)) return false;
            imagepng($this->qrcode, $outfile);  //保存PNG图片到本地
            imagedestroy($this->qrcode); //释放内存
            return true;
        }
    }
}